package com.example.qihuibao.widget.view

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.example.qihuibao.R

class EdittextWithText(ctx: Context, attrs: AttributeSet? = null) : LinearLayout(ctx, attrs) {
    private var tvName:TextView? = null
    private var etContent:EditText? = null
    private var textChange:((text:String)->Unit)? = null
    private var needBack = true

    init {
        val root = LayoutInflater.from(ctx).inflate(R.layout.edittext_text, this, true)
        tvName = root.findViewById(R.id.tv_name)
        etContent = root.findViewById(R.id.et_content)
        etContent?.addTextChangedListener(object:TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable?) {
                if (needBack) {
                    textChange?.invoke(s.toString())
                }else {
                    needBack = true
                }
            }
        })
        val typeArray = context.obtainStyledAttributes(attrs, R.styleable.EdittextWithText)
        tvName?.text = typeArray.getString(R.styleable.EdittextWithText_etname)
        etContent?.text = Editable.Factory.getInstance().newEditable(typeArray.getString(R.styleable.EdittextWithText_etcontent)?:"")
        etContent?.hint = typeArray.getString(R.styleable.EdittextWithText_hint)
        etContent?.isEnabled = typeArray.getBoolean(R.styleable.EdittextWithText_et_enable, true)
        etContent?.inputType = when(typeArray.getString(R.styleable.EdittextWithText_et_inputType)) {
            "textPassword" -> 0x00000081
            "number" -> 0x00000002
            "numberDecimal" -> 0x00002002
            else -> 0x00000001//text
        }
    }

    fun setText(name:String = "", content:String, textChange:(text:String)->Unit) {
        tvName?.text = name
        etContent?.text = Editable.Factory.getInstance().newEditable(content)
        this.textChange = textChange
    }

    fun setContent(content:String) {
        etContent?.text = Editable.Factory.getInstance().newEditable(content)
    }

    fun setContentWithModify(content:String, textChange:(text:String)->Unit) {
        needBack = false
        etContent?.text = Editable.Factory.getInstance().newEditable(content)
        this.textChange = textChange
    }

    fun getContent():String {
        return etContent?.text.toString()
    }

    fun enableContent(enable:Boolean) {
        etContent?.isEnabled = enable
    }

}